package com.ruoyi.lhky.service;

import com.ruoyi.lhky.mapper.ResearchMapper;
import com.ruoyi.lhky.pojo.Research;
import com.ruoyi.lhky.pojo.Tester;
import com.ruoyi.lhky.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;

@Service
public class ResearchService {

    @Autowired
    private ResearchMapper researchMapper;

    public R listByUserAndWorkplace(Long userId, Long workplaceId) {
        List<Research> researchList = researchMapper.searchByUserAndWorkplace(userId, workplaceId);

        Map<Long, Research> uniqueResearchMap = new LinkedHashMap<>();
        for (Research research : researchList) {
            if (!uniqueResearchMap.containsKey(research.getWorkplaceId())) {
                uniqueResearchMap.put(research.getWorkplaceId(), research);
            }
        }

        List<Research> filteredResearchList = uniqueResearchMap.values().stream().collect(Collectors.toList());

        for (Research research : filteredResearchList) {
            int participantCount = researchMapper.countParticipants(research.getId(), research.getWorkplaceId());
            int enrollmentCount = researchMapper.countEnrollments(research.getId(), research.getWorkplaceId());
            int submissionCount = researchMapper.countSubmissions(research.getId(), research.getWorkplaceId());
            research.setParticipantCount(participantCount);
            research.setEnrollmentCount(enrollmentCount);
            research.setSubmissionCount(submissionCount);
        }

        return new R(true, filteredResearchList);
    }

    public R getResearchDetail(Long researchId, Long hospitalId) {
        Research research = researchMapper.findByIdAndHospitalId(researchId, hospitalId);
        if (research == null) {
            return new R(false, "研究项目未找到");
        }

        int participantCount = researchMapper.countParticipants(research.getId(), research.getWorkplaceId());
        int enrollmentCount = researchMapper.countEnrollments(research.getId(), research.getWorkplaceId());
        int submissionCount = researchMapper.countSubmissions(research.getId(), research.getWorkplaceId());
        research.setParticipantCount(participantCount);
        research.setEnrollmentCount(enrollmentCount);
        research.setSubmissionCount(submissionCount);

        return new R(true, research);
    }

    public R getParticipants(Long researchId, Long hospitalId) {
        List<Tester> participants = researchMapper.findParticipantsByResearchIdAndHospitalId(researchId, hospitalId);
        return new R(true, participants);
    }
}
